﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Casamiel.API.Application;
using Casamiel.API.Application.Commands;
using Casamiel.API.Application.Models;
using Casamiel.API.Application.Models.Ele;
using Casamiel.API.Application.Services;
using Casamiel.Application;
using Casamiel.Application.Commands;
using Casamiel.Common;
using Casamiel.Common.Extensions;
using Casamiel.Common.Utilities;
using Casamiel.Domain.Entity;
using Casamiel.Domain.Request;
using Casamiel.Domain.Request.IC;
using Casamiel.Domain.Response;
using Enyim.Caching;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Casamiel.API.Controllers.V2
{
    /// <summary>
    /// 饿了么接口
    /// </summary>
    [Produces("application/json")]
    [ApiVersion("2.0")]
    [Route("api/v{api-version:apiVersion}/[controller]")]
    [ApiController]
    public class EleController : Controller
    {
        private readonly NLog.ILogger logger = NLog.LogManager.GetLogger("ELEOrderService");
        private readonly NLog.ILogger _stocklogger = NLog.LogManager.GetLogger("EleStockService");
        private readonly IIcApiService _icApiService;
        private readonly IStoreApiService _storeApiService;
        private readonly ICasaMielSession _session;
        private readonly IThirdPartyPlatformConfigService _thirdPartyPlatformConfigService;
        private readonly string _apitoken;
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly IMemberCardService _memberCardService;
        private readonly IMemcachedClient _memcachedClient;
        private readonly IMediator _mediator;
        private readonly string _memcachedPre;
        private readonly IErrorLogService _errorLogService;
        private readonly string _apiname;
        private readonly INoticeService _notice;
        private readonly IOrderService _order;
        private readonly string SmsSignName;
        /// <summary>
        /// Initializes a new instance of the <see cref="T:Casamiel.API.Controllers.V2.MeiTuanController"/> class.
        /// </summary>
        /// <param name="iicApiService">Iic API service.</param>
        /// <param name="storeApiService">Store API service.</param>
        /// <param name="session">Session.</param>
        /// <param name="snapshot">snapshot</param>
        /// <param name="thirdPartyPlatformConfigService"></param>
        /// <param name="httpClientFactory"></param>
        /// <param name="memberCardService"></param>
        /// <param name="memcachedClient"></param>
        /// <param name="mediator"></param>
        ///<param name="errorLogService"></param>
        ///<param name="notice"></param>
        ///<param name="order"></param>
        public EleController(IIcApiService iicApiService, IStoreApiService storeApiService, ICasaMielSession session, IOptionsSnapshot<CasamielSettings> snapshot,
                                 IThirdPartyPlatformConfigService thirdPartyPlatformConfigService, IHttpClientFactory httpClientFactory, IMemberCardService memberCardService,
                            IMemcachedClient memcachedClient, IMediator mediator, IErrorLogService errorLogService,
                            INoticeService notice, IOrderService order)
        {
            if (snapshot == null) {
                throw new ArgumentNullException(nameof(snapshot));
            }

            _icApiService = iicApiService;
            _storeApiService = storeApiService;
            _session = session;
            _apiname = snapshot.Value.ApiName;
            _apitoken = snapshot.Value.ApiToken;
            _memcachedPre = snapshot.Value.MemcachedPre;
            _thirdPartyPlatformConfigService = thirdPartyPlatformConfigService;
            _httpClientFactory = httpClientFactory;
            _memberCardService = memberCardService;
            _memcachedClient = memcachedClient;
            _mediator = mediator;
            _errorLogService = errorLogService;
            _notice = notice;
            _order = order;
            SmsSignName = snapshot.Value.Subject;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [ProducesResponseType(typeof(BaseResult<List<MemberCard>>), 200)]
        public async Task<IActionResult> GetMyCard(string mobile)
        {
            var list = await _memberCardService.GetListAsync<ICasaMielSession>(mobile).ConfigureAwait(false);
            var result = new BaseResult<List<MemberCard>>(list);
            return Ok(result);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public IActionResult GetProduct(string cacheKey)
        {

            object a = new object();
            if (_memcachedClient.TryGet(cacheKey, out a)) {
                return Ok(new { t = a });
            }
            return Ok("");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> Icconsumepay([FromBody]IcConsumepayReq data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            if (token != _apitoken) {
                return Ok(new { code = 99999, msg = "token无效" });
            }
            var zmodel = await _icApiService.Icconsumepay(data).ConfigureAwait(false);
            return Ok(zmodel);
        }

        /// <summary>
        /// Thirdorderback the specified ictradeNO.
        /// </summary>
        /// <returns>The thirdorderback.</returns>
        /// <param name="ictradeNO">Ictrade no.</param>
        [HttpPost]
        [Route("[action]")]

        public async Task<IActionResult> Thirdorderback(string ictradeNO)
        {
            //if (token != _apitoken)
            //{
            //    return Ok(new { code = 99999, msg = "token无效" });
            //}
            var backreq = new ThirdOrderBackReq { Tradeno = ictradeNO };
            var back = await _icApiService.ThirdOrderBack(backreq).ConfigureAwait(false);
            //var zmodel = await _icApiService.icconsumeback(new IcConsumeBackDto { tradeno = ictradeNO });
            return Ok(back);
        }



        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> OrderComplateTask()
        {

            var zmodelist = new List<ElmOrderView>();
            //Task task = new Task(async () =>
            //{
            var orderlist = await _order.GetPayedOrderListAsync<ICasaMielSession>(2).ConfigureAwait(false);
            if (orderlist.Any()) {
                var list = orderlist.Where(c => c.CreateTime > DateTime.Now.AddDays(-4)).ToList();
                var count = list.Count;
                for (int i = 0; i < count; i++) {
                    var d = await GetOrderByOrderId(list[i].OrderCode).ConfigureAwait(false);
                    if (d != null) {

                        if (d.Status == "settled") {
                            zmodelist.Add(d);
                        }
                    }

                }
            }
            foreach (var item in zmodelist) {
                var command = new ThirdOrderPickupCommand(item.Id, 2);
                var result = await _mediator.Send(command).ConfigureAwait(false);
                Console.WriteLine(JsonConvert.SerializeObject(result));
            }

            return Ok(zmodelist);
        }        /// <summary>
                 /// 
                 /// </summary>
                 /// <param name="OrderId"></param>
                 /// <returns></returns>

        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GetElmOrder(string OrderId)
        {
            var entity = await GetOrderByOrderId(OrderId).ConfigureAwait(false);
            return Ok(entity);
        }

        /// <summary>
        /// /
        /// </summary>
        /// <param name="OrderId"></param>
        /// <returns></returns>
        private async Task<ElmOrderView> GetOrderByOrderId(string OrderId)
        {
            var source = 0;
            if (SmsSignName == "可莎蜜兒") {
                source = 0;
            }
            if (SmsSignName.Contains("皇冠", StringComparison.OrdinalIgnoreCase)) {
                source = 1;
            }
            var data = new { action = "eleme.order.getOrder", source, @params = new { orderId = $"{OrderId}" } };
            var client = _httpClientFactory.CreateClient("");
            using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, "https://api.casamiel.cn/EleCall") {
                Content = new StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json")

            }) {
                requestMessage.Headers.Add("u-token", "a4b9ebab9bad341d28bf9c84d024b528");

                using (var response = await client.SendAsync(requestMessage).ConfigureAwait(false)) {
                    if (response.IsSuccessStatusCode) {
                        var result1 = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                        var d = JsonConvert.DeserializeObject<ElmOrderResponse>(result1);
                        if (d != null && d.Result != null) {
                            return d.Result;
                        }
                    }
                }
            }
            return null;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tradeNO"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> Getdetail(string tradeNO)
        {
            var model = await _icApiService.Listdetail(new Application.Models.ICModels.ListDetailReq { Tradeno = tradeNO }).ConfigureAwait(false);
            return Ok(model);
        }
        /// <summary>
        /// Geticorderstate the specified tradeNO.
        /// </summary>
        /// <returns>The geticorderstate.</returns>
        /// <param name="tradeNO">Trade no.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> Geticorderstate(string tradeNO)
        {
            var model = await _icApiService.Icorderstate(new Application.Models.IcorderstateReq { Tradeno = tradeNO }).ConfigureAwait(false);
            return Ok(model);
        }

        /// <summary>
        /// Thirdorderback the specified tradeNO.
        /// </summary>
        /// <returns>The thirdorderback.</returns>
        /// <param name="tradeNO">Trade no.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> Testderback(string tradeNO)
        {
            var req = new ThirdOrderBackReq { Tradeno = tradeNO };
            var d = await _icApiService.ThirdOrderBack(req).ConfigureAwait(false);
            return Ok(d);
        }

        /// <summary>
        /// Notify the specified data and token.
        /// </summary>
        /// <returns>The notify.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> Notify([FromBody] NotifyMessageReq data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            logger.Trace($"Notify:{JsonConvert.SerializeObject(data)}");
            //logger.Trace($"u-token:{token}");
            if (token != _apitoken) {
                return Ok(new { code = 99999, msg = "token无效" });
            }
            var shopid = 0;
            var storeinfo = await _thirdPartyPlatformConfigService.FindByEleStoreIdAsync<ICasaMielSession>(data.ShopId).ConfigureAwait(false);
            if (storeinfo != null && storeinfo.EleEnable) {
                shopid = storeinfo.ShopId;
            }
            if (shopid == 0) {
                logger.Trace($"未开通饿了么");
                return Ok(new { code = 0, msg = "", content = "" });
            }
            var orderinfo = JObject.Parse(data.Message);

            var entity = await _order.GetByOrderCodeAsync<ICasaMielSession>(orderinfo["orderId"] != null ? orderinfo["orderId"].ToString() : "00").ConfigureAwait(false);

            switch (data.Type) {
                case 10://  订单生效

                    var _ecachekey = _memcachedPre + Constant.NEWELMORDERID + orderinfo["orderId"].ToString();
                    var trynums = _memcachedClient.Increment(_ecachekey, 1, 1);
                    if (trynums == 1) {
                        var m = await AddOrder(data, shopid).ConfigureAwait(false);
                        if (m.code != 0) {
                            await _memcachedClient.RemoveAsync(_ecachekey).ConfigureAwait(false);
                        }
                        return Ok(m);
                    }
                    return Ok(new { code = 0, msg = "", content = "" });
                case 18://18    订单完结
                case 56:

                    var _cachekey = _memcachedPre + Constant.ELMORDERID + orderinfo["orderId"].ToString();
                    var trynum = _memcachedClient.Increment(_cachekey, 1, 1);
                    //var da = _memcachedClient.GetWithCas(_cachekey);
                    //if (da.Cas == 0)
                    //{
                    //    trynum += 1;
                    //    var resultss = _memcachedClient.Cas(Enyim.Caching.Memcached.StoreMode.Add, _cachekey, trynum);
                    //}
                    //else { 
                    //         trynum = (int)da.Result + 1;
                    //      _memcachedClient.Cas(Enyim.Caching.Memcached.StoreMode.Set, _cachekey, trynum);
                    //}

                    if (trynum == 1) {
                        var OrderComplateResult = await OrderComplate(orderinfo["orderId"].ToString()).ConfigureAwait(false);
                        if (OrderComplateResult.code != 0) {
                            _memcachedClient.Remove(_cachekey);
                            if (OrderComplateResult.code == 8888) {
                                return Ok(new { code = 0, msg = "", content = "" });
                            }
                            return Ok(OrderComplateResult);
                        };
                        // _memcachedClient.Remove(_cachekey);
                    } else {
                        _memcachedClient.Remove(_cachekey);
                        return Ok(new { code = 999, msg = "请重试", content = "" });
                    }

                    //var OrderComplateResult = await OrderComplate(data);
                    //if (OrderComplateResult.code != 0)
                    //{
                    //    return Ok(OrderComplateResult);
                    //}
                    break;
                case 15://订单置为无效(
                case 17://订单强制无效
                case 23://23    商户同意退单
                case 14://14    订单被取消（接单前）
                case 57://配送取消,商户取消
                    var zmodel = await OrderCancel(data).ConfigureAwait(false);
                    if (zmodel.code != 0) {
                        return Ok(zmodel);
                    }
                    break;
                case 91://店铺营业状态变化

                    return Ok(new { code = 0, msg = "", content = "" });
                default:
                    break;
            }

            var result = await _storeApiService.EleNotifyAsync(data).ConfigureAwait(false);
            logger.Trace($" _storeApiService.EleNotify:{JsonConvert.SerializeObject(result)}");

            if (entity != null && entity.OrderStatus == (int)OrderStatus.Completed) {
                using (var uow = _session.UnitOfWork(IsolationLevel.Serializable)) {
                    await _order.OrderBaseUPdateAsync(entity, uow).ConfigureAwait(true);
                }
            }
            return Ok(result);
            //var dynamicdata = JsonConvert.DeserializeObject<JObject>(result);
            //if (dynamicdata["ResultNo"].ToString() == "00000000") {
            //    return Ok(new { code = 0, msg = "" });
            //}
            //if (dynamicdata["ResultNo"].ToString() == "06010007") {
            //    return Ok(new { code = 0, msg = "" });
            //}
            //return Ok(new { code = 9999, msg = dynamicdata["ResultRemark"].ToString() });
            //var d = JObject.Parse(data.message);
            //return Ok(d);
        }
        private async Task<Zmodel> OrderComplate(string orderCode)
        {
            var entity = await _order.GetByOrderCodeAsync<ICasaMielSession>(orderCode).ConfigureAwait(false);
            if (entity == null) {
                return new Zmodel { code = 0, msg = "订单不存在" };
            }
            if (entity.Status == 7) {
                return new Zmodel { code = 0, msg = "订单已经完成" };
            }
            var command = new ThirdOrderPickupCommand(orderCode, 2);
            var result = await _mediator.Send(command).ConfigureAwait(false);
            return result;
        }
        /// <summary>
        /// Picup the specified ordercode and token.
        /// </summary>
        /// <returns>The picup.</returns>
        /// <param name="ordercode">Ordercode.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<ActionResult<Zmodel>> Picup(string ordercode, [FromHeader(Name = "u-token")] string token)
        {
            if (ordercode == null) {
                throw new ArgumentNullException(nameof(ordercode));
            }

            if (token != _apitoken) {
                return Ok(new { code = 99999, msg = "token无效" });
            }
            List<string> aaaa = ordercode.Split(' ').ToList();
            foreach (var item in aaaa) {
                var entity = await _order.GetByOrderCodeAsync<ICasaMielSession>(item).ConfigureAwait(false);
                if (entity == null) {
                    return new Zmodel { code = 0, msg = "订单不存在" };
                }

                //if (entity.OrderStatus == 7)
                //{
                //    return new Zmodel { code = 0, msg = "订单完成" };
                //}
                IcorderpickupReq dto = new IcorderpickupReq() {
                    Phoneno = entity.ContactPhone,
                    Tradeno = entity.IcTradeNO
                };
                var d = await _icApiService.Icorderpickup(dto).ConfigureAwait(false);
                logger.Trace($"icorderpickup,req:{JsonConvert.SerializeObject(dto)},rsp:{JsonConvert.SerializeObject(d)}");
                if (d.code == 0) {
                    var jobject = JsonConvert.DeserializeObject<JObject>(d.content);
                    var billno = jobject["billno"].ToString();

                    await _order.UpdateOrderStatusAndResBillNOAsync<ICasaMielSession>(entity.OrderBaseId, 7, billno).ConfigureAwait(false);

                }
            }
            return Ok();
        }
        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>

        private async Task<Zmodel> OrderCancel(NotifyMessageReq data)
        {
            var orderinfo = JObject.Parse(data.Message);
            var type = data.Type;
            var command = new CancelOrderCommand(orderinfo["orderId"].ToString(), 2, "", "");
            var result = await _mediator.Send(command).ConfigureAwait(false);
            return result;

        }
        private async Task<Zmodel> AddOrder(NotifyMessageReq req, int shopid = 0)
        {
            var data = JsonConvert.DeserializeObject<ElmOrderView>(req.Message);

            //List<string> blacklist = new List<string>();
            //var drink = await _storeApiService.GetDrinksGoodsId().ConfigureAwait(false);
            //var rnt = JObject.Parse(drink);
            //if (rnt["ResultNo"].ToString() == "00000000")// "ResultNo": "00000000",
            //{
            //    blacklist = JsonConvert.DeserializeObject<List<string>>(rnt["Data"].ToString());
            //}

            var d = new GetDrinksGoodsIdsCommand();
            var blacklist = await _mediator.Send(d).ConfigureAwait(false);

            var ptprice = new IcPriceReq { Shopid = shopid, Product = new List<ProductItemReq>() };
            var skus = new Dictionary<string, int>();
            var listItem = data.Groups.Where(c => c.Name != "其它费用").ToList();

            var goodstototal = 0m;
            string errorinfo = "";
            foreach (var item in listItem) {
                goodstototal += item.Items.Sum(c => c.Quantity * c.Price);
                foreach (var p in item.Items) {

                    if (string.IsNullOrEmpty(p.ExtendCode)) {
                        errorinfo += $"{p.Name},sku 不存在";
                    }
                    if (skus.ContainsKey(p.ExtendCode)) {
                        int count = skus[p.ExtendCode];
                        skus.Remove(p.ExtendCode);
                        skus.Add(p.ExtendCode, count + p.Quantity);
                    } else {
                        skus.Add(p.ExtendCode, p.Quantity);
                        ptprice.Product.Add(new ProductItemReq { Pid = p.ExtendCode, Count = p.Quantity });
                    }
                }
            }
            if (!string.IsNullOrEmpty(errorinfo)) {
                var info = $"{shopid},饿了么订单号：{data.OrderId},{errorinfo},";
                await _errorLogService.AddAsync<ICasaMielSession>(new Domain.ErrorLog { Url = "", Loginfo = info, OPTime = DateTime.Now, Type = 2 }).ConfigureAwait(false);

                return new Zmodel { code = 999, msg = "商品下架" };
            }
            var goodsOrderoriginprice = 0m;
            var pzmodel = await _icApiService.Icprice(ptprice).ConfigureAwait(false);
            if (pzmodel.Product.Count > 0) {
                foreach (var item in skus) {
                    var iteminfo = pzmodel.Product.Find(cw => cw.Pid == item.Key);

                    if (iteminfo == null) {
                        logger.Error($"sku{item.Key}不存在");
                        return new Zmodel { code = 999, msg = "商品下架" };
                    }
                    goodsOrderoriginprice += iteminfo.Icprice * item.Value;
                }
            } else {
                logger.Error($"商品下架");
                return new Zmodel { code = 999, msg = "商品下架" };
            }


            var orderentity = await _order.GetByOrderCodeAsync<ICasaMielSession>(data.OrderId).ConfigureAwait(false);
            if (orderentity != null) {
                return new Zmodel { code = 0, msg = "订单已存！" };
            }
            var ictradeNO = "";
            var billNO = "";
            //var discu = 0;// Orderoriginprice - data.t.ToDecimal(0) / 100 + data.orderDiscountMoney.ToDecimal(0) / 100;

            //  var Rebate = data.originalPrice - data.totalPrice+data.hongbao;
            var Rebate = goodsOrderoriginprice - goodstototal;
            var icdto = new IcconsumeReq { Cardno = "", Rebate = Rebate.ToString(CultureInfo.CurrentCulture).ToDouble(0), Shopid = shopid, Pickuptime = data.DeliverTime.HasValue ? data.DeliverTime.Value.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.CurrentCulture) : DateTime.Now.AddMinutes(20).ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.CurrentCulture) };
            icdto.Product = new List<IcconsumeReq.IcconsumeProductItem>();
            foreach (KeyValuePair<string, int> kvp in skus) {
                icdto.Product.Add(new IcconsumeReq.IcconsumeProductItem { Pid = kvp.Key, Count = kvp.Value, Pname = "" });
            }

            // return new Zmodel { code = 0, msg = "" };
            var icentity = await _icApiService.ThirdOrder(icdto).ConfigureAwait(false);
            logger.Trace($"thirdorder，Result:{JsonConvert.SerializeObject(icentity)}，req：{JsonConvert.SerializeObject(icdto)}");
            if (icentity.code == 0) {
                var jobject = JsonConvert.DeserializeObject<JObject>(icentity.content);
                ictradeNO = jobject["tradeno"].ToString();
                billNO = jobject["billno"].ToString();
                req.IcTradeNo = ictradeNO;
                req.BillNo = billNO;
            } else {
                return icentity;
            }

            // if (_apiname == "hgspApi") {
            try {

                var pay = new IcConsumepayReq {
                    Shopid = shopid,
                    Tradeno = ictradeNO,
                    Createinvoice = true
                };
                pay.Paycontent = new List<IcConsumepayReq.PaycontentItem>
                {
                            new IcConsumepayReq.PaycontentItem
                            {
                                Paytype = "10",
                                Paymoney = data.OriginalPrice.ToString(CultureInfo.CurrentCulture).ToDouble(0),
                                Paytradeno = $"{data.OrderId}C{DateTime.Now.ToString("ssffff", CultureInfo.CurrentCulture)}"
                            }
                        };
                pay.Payfee = new List<IcConsumepayReq.PayfeeItem>();
                if (data.DeliverFee - data.VipDeliveryFeeDiscount > 0) {
                    pay.Payfee.Add(new IcConsumepayReq.PayfeeItem { Feetype = "1", Fee = (data.DeliverFee - data.VipDeliveryFeeDiscount).ToString(CultureInfo.CurrentCulture).ToDouble(0), Description = "配送费" });//配送费
                }
                if (data.PackageFee > 0) {
                    pay.Payfee.Add(new IcConsumepayReq.PayfeeItem { Feetype = "2", Fee = data.PackageFee.ToString(CultureInfo.CurrentCulture).ToDouble(0), Description = "包装费" });//包装费
                }


                var invoiceUrl = "";
                var zmodel = await _icApiService.Icconsumepay(pay).ConfigureAwait(false);
                logger.Trace($"icconsumepay，Result:{JsonConvert.SerializeObject(zmodel)}，req:{JsonConvert.SerializeObject(pay)}");
                if (zmodel.code == 0) {
                    var jobject = JsonConvert.DeserializeObject<JObject>(zmodel.content);
                    invoiceUrl = jobject["invoiceqrcode"].ToString();
                     
                  
                } else {
                    var info = $"订单号：{data.OrderId},{JsonConvert.SerializeObject(zmodel)}";
                    await _errorLogService.AddAsync<ICasaMielSession>(new Domain.ErrorLog { Url = Request.GetShortUri(), Loginfo = info, OPTime = DateTime.Now, Type = 2 }).ConfigureAwait(false);

                    logger.Error(zmodel.msg);
                    var backreq = new ThirdOrderBackReq { Tradeno = ictradeNO };
                    var back = await _icApiService.ThirdOrderBack(backreq).ConfigureAwait(false);
                    logger.Trace($"thirdorderback,req:{JsonConvert.SerializeObject(backreq)},result:{JsonConvert.SerializeObject(back)}");
                     
                    return back;
                }


                var cmd = new ElmNotifyCommand() {
                    AppId = req.AppId,
                    IcTradeNo = ictradeNO,
                    Message = req.Message,
                    ShopId = req.ShopId,
                    Signature = req.Signature,
                    Timestamp = req.Timestamp,
                    RequestId = req.RequestId,
                    Type = req.Type,
                    UserId = req.UserId,
                    BillNo = req.BillNo,
                    InvoiceUrl=invoiceUrl
                };
                var result = await _mediator.Send(cmd).ConfigureAwait(false);
                logger.Trace($"AddOrder:{JsonConvert.SerializeObject(result)}");

                if (result.Code == 0) {
                    //var order = await _order.GetByOrderCodeAsync<ICasaMielSession>($"{data.OrderId}").ConfigureAwait(false);
                    //using (var uow = _session.UnitOfWork(IsolationLevel.Serializable)) {
                    //    var noticEntity = new NoticeBaseEntity() {
                    //        RemindTime = DateTime.Now.AddMinutes(-3),
                    //        CreateTime = DateTime.Now,
                    //        RelationId = order.OrderBaseId,
                    //        StoreId = order.StoreId,
                    //        NoticeType = 0
                    //    };
                    //    await _notice.AddAsync(noticEntity, uow).ConfigureAwait(false);
                    //}
                    return new Zmodel { code = 0, msg = "" };
                } else {
                    var backreq = new ThirdOrderBackReq { Tradeno = ictradeNO };
                    var back = await _icApiService.ThirdOrderBack(backreq).ConfigureAwait(false);
                    logger.Trace($"thirdorderback,req:{JsonConvert.SerializeObject(backreq)},result:{JsonConvert.SerializeObject(back)},addelm:{ result.Msg}");
                    await _order.DeleteAsync<ICasaMielSession>($"{data.OrderId}").ConfigureAwait(false);
                    return new Zmodel { code = 9999 };//, msg = dynamicdata["ResultRemark"].ToString() };
                }
            } catch {

                var backreq = new ThirdOrderBackReq { Tradeno = ictradeNO };
                var back = await _icApiService.ThirdOrderBack(backreq).ConfigureAwait(false);
                logger.Trace($"thirdorderback,req:{JsonConvert.SerializeObject(backreq)},result:{JsonConvert.SerializeObject(back)}");
                if (back.code == 0) {
                    var r = await _storeApiService.OrderDelete($"{data.OrderId}").ConfigureAwait(false);
                    await _order.DeleteAsync<ICasaMielSession>($"{data.OrderId}").ConfigureAwait(false);
                    logger.Trace($"OrderDelete:{r}");
                }
                throw;
            }
            //}

            //else {
            //    try {
            //        var result = await _storeApiService.EleNotify(req).ConfigureAwait(false);
            //        logger.Trace($"AddOrder:{result}");
            //        var dynamicdata = JsonConvert.DeserializeObject<JObject>(result);
            //        if (dynamicdata["ResultNo"].ToString() == "00000000") {
            //            var pay = new IcConsumepayReq {
            //                shopid = shopid,
            //                tradeno = ictradeNO,
            //                createinvoice = true
            //            };
            //            pay.paycontent = new List<IcConsumepayReq.Paycontent>
            //            {
            //                new IcConsumepayReq.Paycontent
            //                {
            //                    paytype = "10",
            //                    paymoney = data.originalPrice.ToString(CultureInfo.CurrentCulture).ToDouble(0),
            //                    paytradeno = $"{data.orderId}C{DateTime.Now.ToString("ssffff", CultureInfo.CurrentCulture)}"
            //                }
            //            };
            //            pay.payfee = new List<IcConsumepayReq.Payfee>();
            //            if (data.deliverFee - data.vipDeliveryFeeDiscount > 0) {
            //                pay.payfee.Add(new IcConsumepayReq.Payfee { feetype = "1", fee = (data.deliverFee - data.vipDeliveryFeeDiscount).ToString(CultureInfo.CurrentCulture).ToDouble(0), description = "配送费" });//配送费
            //            }
            //            if (data.packageFee > 0) {
            //                pay.payfee.Add(new IcConsumepayReq.Payfee { feetype = "2", fee = data.packageFee.ToString(CultureInfo.CurrentCulture).ToDouble(0), description = "包装费" });//包装费
            //            }

            //            //if (data.activityTotal > 0)
            //            //{
            //            //    pay.payfee.Add(new IcConsumepayDto.Payfee { feetype = "3", fee = data.activityTotal.ToString().ToDouble(0), description = "第三方平台积分抵扣金额" });//第三方平台抵扣金额 
            //            //}
            //            //if (data.hongbao > 0)
            //            //{
            //            //    pay.payfee.Add(new IcConsumepayDto.Payfee { feetype = "3", fee = data.hongbao.ToString().ToDouble(0), description = "红包" });// 
            //            //}

            //            var zmodel = await _icApiService.Icconsumepay(pay).ConfigureAwait(false);
            //            logger.Trace($"icconsumepay，Result:{JsonConvert.SerializeObject(zmodel)}，req:{JsonConvert.SerializeObject(pay)}");
            //            if (zmodel.code == 0) {
            //                var jobject = JsonConvert.DeserializeObject<JObject>(zmodel.content);
            //                var invoiceUrl = jobject["invoiceqrcode"].ToString();
            //                await _order.UpdateOrderInvoiceUrlByOrderCodeAsync<ICasaMielSession>(data.orderId, invoiceUrl).ConfigureAwait(false);

            //                var order = await _order.GetByOrderCodeAsync<ICasaMielSession>(data.orderId).ConfigureAwait(false);
            //                using (var uow = _session.UnitOfWork(IsolationLevel.Serializable)) {
            //                    var noticEntity = new NoticeBaseEntity() {
            //                        RemindTime = DateTime.Now.AddMinutes(-3),
            //                        CreateTime = DateTime.Now,
            //                        RelationId = order.OrderBaseId,
            //                        StoreId = order.StoreId,
            //                        NoticeType = 0
            //                    };
            //                    await _notice.AddAsync(noticEntity, uow).ConfigureAwait(false);
            //                }
            //                return new Zmodel { code = 0, msg = "" };
            //            } else {
            //                var backreq = new ThirdOrderBackReq { tradeno = ictradeNO };
            //                var back = await _icApiService.ThirdOrderBack(backreq).ConfigureAwait(false);
            //                logger.Trace($"thirdorderback,req:{JsonConvert.SerializeObject(backreq)},result:{JsonConvert.SerializeObject(back)}");
            //                if (back.code == 0) {
            //                    var r = await _storeApiService.OrderDelete(data.orderId).ConfigureAwait(false);
            //                    logger.Trace($"OrderDelete:{r}");
            //                }
            //                return back;
            //            }
            //        } else {
            //            var backreq = new ThirdOrderBackReq { tradeno = ictradeNO };
            //            var back = await _icApiService.ThirdOrderBack(backreq).ConfigureAwait(false);
            //            logger.Trace($"thirdorderback,req:{JsonConvert.SerializeObject(backreq)},result:{JsonConvert.SerializeObject(back)},addelm:{ dynamicdata["ResultRemark"].ToString()}");

            //            return new Zmodel { code = 9999 };//, msg = dynamicdata["ResultRemark"].ToString() };
            //        }
            //    } catch {

            //        // logger.Error($"AddJdOrder:{ex.StackTrace}");
            //        var backreq = new ThirdOrderBackReq { tradeno = ictradeNO };
            //        var back = await _icApiService.ThirdOrderBack(backreq).ConfigureAwait(false);
            //        logger.Trace($"thirdorderback,req:{JsonConvert.SerializeObject(backreq)},result:{JsonConvert.SerializeObject(back)}");
            //        if (back.code == 0) {
            //            var r = await _storeApiService.OrderDelete(data.orderId).ConfigureAwait(false);
            //            logger.Trace($"OrderDelete:{r}");
            //        }
            //        throw;
            //    }
            //}
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[Action]")]
        public async Task<IActionResult> SetAllproductStock([FromHeader(Name = "u-token")] string token)
        {
            if (token != _apitoken) {
                return Ok(new { code = 99999, msg = "token无效" });
            }
            var listAll = await _thirdPartyPlatformConfigService.GetAllAsync<ICasaMielSession>().ConfigureAwait(false);
            var source = 0;
            if (_apiname == "hgspApi") {
                source = 1;
            }
            var list = listAll.Where(c => c.EleEnable == true).ToList();
            foreach (var l in list) {
                // "releationId": 222161,"shopId": 163124893

                var data = new { source = source, releationId = l.ShopId };

                using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"/api/v1/Ele/UPdate") {
                    Content = new StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json")
                }) {
                    requestMessage.Headers.Add("u-token", _apitoken);
                    //requestMessage.Headers.Add("Content-Type", "application/json");
                    var client = _httpClientFactory.CreateClient("MentuanOpen");
                    using (var response = await client.SendAsync(requestMessage).ConfigureAwait(false)) {
                        var reslut = "";
                        if (response.IsSuccessStatusCode) {
                            reslut = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                        }
                        _stocklogger.Trace($"{l.ShopName }-{reslut}");
                    }
                }


            }
            //});
            // task.Start();
            return Ok("");
        }
        /// <summary>
        /// Setproduct this instance.
        /// </summary>
        /// <returns>The setproduct.</returns>
        [HttpPost]
        [Route("[Action]")]
        public async Task<IActionResult> SetAllproduct()
        {
            var begin = DatetimeUtil.GetUnixTime(DateTime.Now, TimePrecision.Millisecond);

            var listAll = await _thirdPartyPlatformConfigService.GetAllAsync<ICasaMielSession>().ConfigureAwait(false);

            //Task task = new Task(async () => {
            var source = 0;
            if (_apiname == "hgspApi") {
                source = 1;
            }
            var list = listAll.Where(c => c.EleEnable == true).ToList();


            int pagesize = Math.Ceiling(Convert.ToDecimal(list.Count) / 4).ToString(CultureInfo.CurrentCulture).ToInt32(0);
            //   await Task.Run(async () =>
            //{

            var backgroundTasks = new[]
            {
                 Task.Run(async () =>
                {

                    var t = list.Skip(0).Take(pagesize);
                foreach (var item in t)
                {
            try {
                    var data = new { source = source, releationId = item.ShopId, shopId = item.EleStoreId };

                    using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"/api/v1/Ele/GetqueryBaseListByEPoiId") {
                        Content = new StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json")
                    }) {
                        requestMessage.Headers.Add("u-token", _apitoken);
                        //requestMessage.Headers.Add("Content-Type", "application/json");
                        var client = _httpClientFactory.CreateClient("MentuanOpen");
                        using (var response = await client.SendAsync(requestMessage).ConfigureAwait(false)) {
                            if (response.IsSuccessStatusCode) {
                                var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                                var list1 = JsonConvert.DeserializeObject<List<string>>(result);
                                _stocklogger.Trace($"{item.ShopId}-{item.ShopName}:{string.Join(',', list1)}");
                            }
                        }
                    }
                } catch (Exception ex) {
                    _stocklogger.Error($"{item.ShopId}-{item.ShopName}{ex.StackTrace}");
                }
                }
                return "task";
            }),
                  Task.Run(async () =>
                {

                    var t = list.Skip(pagesize).Take(pagesize);
                foreach (var item in t)
                {
            try {
                    var data = new { source = source, releationId = item.ShopId, shopId = item.EleStoreId };

                    using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"/api/v1/Ele/GetqueryBaseListByEPoiId") {
                        Content = new StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json")
                    }) {
                        requestMessage.Headers.Add("u-token", _apitoken);
                        //requestMessage.Headers.Add("Content-Type", "application/json");
                        var client = _httpClientFactory.CreateClient("MentuanOpen");
                        using (var response = await client.SendAsync(requestMessage).ConfigureAwait(false)) {
                            if (response.IsSuccessStatusCode) {
                                var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                                var list1 = JsonConvert.DeserializeObject<List<string>>(result);
                                _stocklogger.Trace($"{item.ShopId}-{item.ShopName}:{string.Join(',', list1)}");
                            }
                        }
                    }
                } catch (Exception ex) {
                    _stocklogger.Error($"{item.ShopId}-{item.ShopName}{ex.StackTrace}");
                }
                }
                return "task2";
            }),
                   Task.Run(async () =>
                {

                    var t = list.Skip(2*pagesize).Take(pagesize);
                foreach (var item in t)
                {
            try {
                    var data = new { source = source, releationId = item.ShopId, shopId = item.EleStoreId };

                    using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"/api/v1/Ele/GetqueryBaseListByEPoiId") {
                        Content = new StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json")
                    }) {
                        requestMessage.Headers.Add("u-token", _apitoken);
                        //requestMessage.Headers.Add("Content-Type", "application/json");
                        var client = _httpClientFactory.CreateClient("MentuanOpen");
                        using (var response = await client.SendAsync(requestMessage).ConfigureAwait(false)) {
                            if (response.IsSuccessStatusCode) {
                                var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                                var list1 = JsonConvert.DeserializeObject<List<string>>(result);
                                _stocklogger.Trace($"{item.ShopId}-{item.ShopName}:{string.Join(',', list1)}");
                            }
                        }
                    }
                } catch (Exception ex) {
                    _stocklogger.Error($"{item.ShopId}-{item.ShopName}{ex.StackTrace}");
                }
                }
                return "task3";
            }),
                    Task.Run(async () =>
                {

                    var t = list.Skip(pagesize*3).Take(pagesize);
                foreach (var item in t)
                {
            try {
                    var data = new { source = source, releationId = item.ShopId, shopId = item.EleStoreId };

                    using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"/api/v1/Ele/GetqueryBaseListByEPoiId") {
                        Content = new StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json")
                    }) {
                        requestMessage.Headers.Add("u-token", _apitoken);
                        //requestMessage.Headers.Add("Content-Type", "application/json");
                        var client = _httpClientFactory.CreateClient("MentuanOpen");
                        using (var response = await client.SendAsync(requestMessage).ConfigureAwait(false)) {
                            if (response.IsSuccessStatusCode) {
                                var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                                var list1 = JsonConvert.DeserializeObject<List<string>>(result);
                                _stocklogger.Trace($"{item.ShopId}-{item.ShopName}:{string.Join(',', list1)}");
                            }
                        }
                    }
                } catch (Exception ex) {
                    _stocklogger.Error($"{item.ShopId}-{item.ShopName}{ex.StackTrace}");
                }
                }
                return "task4";
            })
            };

            try {
                var completedTask = await Task.WhenAll(backgroundTasks).ConfigureAwait(true);
                var result = completedTask;
                _stocklogger.Trace($"{string.Join(',',result)}");
                var end = DatetimeUtil.GetUnixTime(DateTime.Now, TimePrecision.Millisecond);
                _stocklogger.Trace($"ComplateTask,执行时间{end - begin}毫秒");
            } catch (AggregateException ex) {
                foreach (var item in ex.InnerExceptions) {
                    _stocklogger.Error(string.Format(CultureInfo.CurrentCulture, "异常类型：{0}{1}来自：  {2} {3} 异常内容：{4}", item.GetType(),
                Environment.NewLine, item.Source,
                Environment.NewLine, item.Message));

                }

            }



            //foreach (var l in list) {
            //    // "releationId": 222161,"shopId": 163124893
            //    try {
            //        var data = new { source = source, releationId = l.ShopId, shopId = l.EleStoreId };

            //        using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"/api/v1/Ele/GetqueryBaseListByEPoiId") {
            //            Content = new StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json")
            //        }) {
            //            requestMessage.Headers.Add("u-token", _apitoken);
            //            //requestMessage.Headers.Add("Content-Type", "application/json");
            //            var client = _httpClientFactory.CreateClient("MentuanOpen");
            //            using (var response = await client.SendAsync(requestMessage).ConfigureAwait(false)) {
            //                if (response.IsSuccessStatusCode) {
            //                    var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            //                    var list1 = JsonConvert.DeserializeObject<List<string>>(result);
            //                    _stocklogger.Trace($"{l.ShopId}-{l.ShopName}:{string.Join(',', list1)}");
            //                }
            //            }
            //        }
            //    } catch (Exception ex) {
            //        _stocklogger.Error($"{l.ShopId}-{l.ShopName}{ex.StackTrace}");
            //    }
            //}
            //});
            // task.Start();
            return Ok("");
        }
        /// <summary>
        /// Setproducts the by shop identifier.
        /// </summary>
        /// <returns>The by shop identifier.</returns>
        /// <param name="shopid">Shopid.</param>
        [HttpPost]
        [Route("[Action]")]
        [ProducesResponseType(typeof(BaseResult<string>), 200)]
        public async Task<IActionResult> SetproductByShopId(int shopid)
        {
            var source = 0;
            if (_apiname == "hgspApi") {
                source = 1;
            }
            var result = "";
            var entity = await _thirdPartyPlatformConfigService.FindAsync<ICasaMielSession>(shopid).ConfigureAwait(false);
            if (entity != null) {
                var data = new { source, releationId = entity.ShopId, shopId = entity.EleStoreId };
                using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"/api/v1/Ele/GetqueryBaseListByEPoiId") {
                    Content = new StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json")
                }) {
                    requestMessage.Headers.Add("u-token", _apitoken);
                    var client = _httpClientFactory.CreateClient("MentuanOpen");
                    using (var response = await client.SendAsync(requestMessage).ConfigureAwait(false)) {
                        if (response.IsSuccessStatusCode) {
                            result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                            var list1 = JsonConvert.DeserializeObject<List<string>>(result);
                            result = entity.ShopId + "-" + entity.ShopName + ":" + string.Join(',', list1);
                            logger.Trace(result);
                        }
                    }
                }
            }
            var aa = new BaseResult<string>(result, 0, "");
            return Ok(aa);
        }


    }


}
